using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Sql;
using System.Data.SqlClient;
using QuoteTree;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading;


public partial class QuoteTreeDetails : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
        if (Session.IsNewSession)
        {
            // If it says it is a new session, but an existing cookie exists, then it must 
            // have timed out (can't use the cookie collection because even on first 
            // request it already contains the cookie (request and response
            // seem to share the collection)
            string szCookieHeader = Request.Headers["Cookie"];
            if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
            {
                Response.Redirect("sessionTimeout.aspx");
            }
        }


		if (this.Session["tree"] != null)
		{
			QTree tree;
			tree = this.Session["tree"] as QTree; tree.Root.selected = true;
			string text = "";
			string[] list = tree.GetSelectionsString(tree.Root,0).Split("|".ToCharArray());
            int c = 0;
			foreach (string s in list)
			{
                if (c == 1)
                {
                    string s1 = s;//.Trim();
                    if (s1 != "")
                    {
                        text += s1.Replace("\n", "").Replace("\r", "").Remove(0, 2).Replace(" ", "&nbsp;") + "<BR>";// +"<HR size=1>";
                    }
                }
                c = 1;

			}
			if (!tree.Root.IsComplete()) this.Button1.Enabled = this.Button2.Enabled = false;
			string url = "print_quote.aspx" ;
			if (this.Request.QueryString["quote"] != null && this.Request.QueryString["quote"].ToString() != "")
				url += "?quote=" + this.Request.QueryString["quote"].ToString();
			else this.HyperLink1.Visible = false;

			if (this.Request.QueryString["revision"] != null && this.Request.QueryString["revision"].ToString() == "yes")
			{
				url += "&revision=" + this.Request.QueryString["revision"].ToString();
				this.Button2.Text = "Accept revision";
				this.HyperLink1.Visible = false;
			}

			if (this.Request.QueryString["quote"] != null && this.Request.QueryString["quote"].ToString() != ""
				&& !(this.Request.QueryString["revision"] != null && this.Request.QueryString["revision"].ToString() == "yes"))
				this.Button2.Visible = false;

			this.HyperLink1.Attributes.Add("onclick", "javascript:window.open('" + url + "' , 'Print', 'HEIGHT=600, WIDTH=800, status=0 , resizable=yes, menubar=no, scrollbars=yes');");

            this.Literal1.Text = text ;


		}
	}
	protected void Button1_Click(object sender, EventArgs e)
	{
		this.Response.Redirect("success.aspx?message=Feature still not available.");
	}
	protected void Button2_Click(object sender, EventArgs e)
	{
        if (this.Session["user"] != null)
        {
            QTree tree;
            tree = this.Session["tree"] as QTree;
            tree.Serialize();

            SqlConnection conn = new SqlConnection(qman.DataHelp.DataAccess.myConnectionString);
            SqlCommand execProc;
            //string cmp = "";
            string quote = "";
            execProc = new SqlCommand("new_quote", conn);
            execProc.CommandType = CommandType.StoredProcedure;

            //if (this.Request.QueryString["cmp_id"] != null)
            //    cmp = this.Request.QueryString["cmp_id"].ToString().Replace("'", "~");

            if (this.Request.QueryString["quote"] != null)
            {
                quote = this.Request.QueryString["quote"].ToString().Replace("'", "~");
                //DataSet ds = qman.DataHelp.DataAccess.getDataSet("select cmp_id, revision from adtech_quotes where id = " + quote);
                //if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                //{
                //    cmp = ds.Tables[0].Rows[0][0].ToString();
                //    if (ds.Tables[0].Rows[0][1] != null && ds.Tables[0].Rows[0][1].ToString() != "") quote = ds.Tables[0].Rows[0][1].ToString();
                //}
            }

            //execProc.Parameters.Add("@id", SqlDbType.VarChar, 25).Value = this.TextBox1.Text.Trim().Replace("'", "~");
            //execProc.Parameters.Add("@project", SqlDbType.VarChar, 25).Value = this.TextBox1.Text.Trim().Replace("'", "~");
            //execProc.Parameters.Add("@cmp_id", SqlDbType.UniqueIdentifier).Value = new Guid(cmp.Replace("'", "~"));
            //execProc.Parameters.Add("@active", SqlDbType.VarChar, 3).Value = "yes";
            execProc.Parameters.Add("@date", SqlDbType.DateTime).Value = System.DateTime.Now;
            //execProc.Parameters.Add("@created_by", SqlDbType.VarChar, 100).Value = this.Session["user"].ToString();
            execProc.Parameters.Add("@total", SqlDbType.Real).Value = tree.Root.total();
            execProc.Parameters.Add("@product_name", SqlDbType.VarChar, 100).Value = tree.Root.name;
            execProc.Parameters.Add("@quote", SqlDbType.VarBinary, 1000000).Value = tree.Serialize().ToArray();
            execProc.Parameters.Add("@item", SqlDbType.VarChar, 100).Value = tree.Root.name;
            execProc.Parameters.Add("@user", SqlDbType.VarChar, 100).Value = this.Session["user"].ToString();
            //execProc.Parameters.Add("@company", SqlDbType.VarChar, 100).Value = this.Session["company"].ToString();



            //If it is a revision then insert the quote as a revision of the original quote.
            if (this.Request.QueryString["revision"] != null && this.Request.QueryString["revision"].ToString() == "yes" && quote != "")
                execProc.Parameters.Add("@revision", SqlDbType.Int).Value = quote;
            else execProc.Parameters.Add("@revision", SqlDbType.Int).Value = DBNull.Value;

            try
            {
                conn.Open();
                execProc.ExecuteScalar();

                //Create a thread to send an email to company and client
                Thread t = new Thread(new ThreadStart(SendMail));
                t.Priority = ThreadPriority.Highest;
                t.Start();

            }
            catch (Exception)
            {
                this.Response.Write("Error inserting quote. Please contact webmaster@adtechintl.com");
            }
            finally 
            {
                conn.Close();
            }

            string script = "";
            script += "<script language=JavaScript>";
            script += "self.parent.location='ViewPriceQuotes.aspx';";
            script += "</script>";
            this.RegisterClientScriptBlock("redirect", script);

            //this.Response.Redirect("success.aspx?message=Quoted added to My Wish list.");
        }
	}

    private void SendMail()
    {
        try
        {
            QTree tree;
            tree = this.Session["tree"] as QTree;

            DataSet ds = qman.DataHelp.DataAccess.getDataSet("select email from company_accounts where [user] = '" + this.Session["company"].ToString() + "'");
            DataSet ds1 = qman.DataHelp.DataAccess.getDataSet("select first_name, last_name, email, phone from user_accounts where [user] = '" + this.Session["user"].ToString() + "'");

            string company_email = ds.Tables[0].Rows[0][0].ToString();
            string user_email = ds1.Tables[0].Rows[0][2].ToString();
            string user_phone = ds1.Tables[0].Rows[0][3].ToString();
            string first_name = ds1.Tables[0].Rows[0][0].ToString();
            string last_name = ds1.Tables[0].Rows[0][1].ToString();

            SmtpClient ss = new SmtpClient("smtp.gmail.com", 587);
            ss.EnableSsl = true;
            ss.Timeout = 1000000;
            ss.DeliveryMethod = SmtpDeliveryMethod.Network;
            ss.UseDefaultCredentials = false;
            ss.Credentials = new NetworkCredential("alejandro.penate@gmail.com", "esenpumasiil14");

            MailMessage mm = new MailMessage();
            mm.Subject = "New price quote";
            mm.From = new MailAddress("alejandro.penate@gmail.com", "Online Pricing System");
            mm.To.Add(company_email);
            mm.To.Add(user_email);
            mm.Body = "<b>From:</b> " + first_name + " " + last_name
                + "<BR>" + "<b>Email:</b> " + user_email
                + "<BR>" + "<b>Phone:</b> " + user_phone
                + "<BR>" + "<b>Product:</b> " + tree.Root.name
                + "<BR>" + "<b>Price:</b> " + Decimal.Round(tree.Root.total(), 2).ToString("C")
                + "<BR><BR>" + this.Literal1.Text;
            mm.IsBodyHtml = true;
            //mm.BodyEncoding = UTF8Encoding.UTF8;
            //mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
            ss.Send(mm);
        }
        catch (Exception) { }
 
    }
}
